package com.heima.comment.service.impl;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private GreenScan greenScan;

    /**
     * 查看更多回复内容
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        if (dto.getCommentId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
        //未登录分页查询
        //根据文章id查询

        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()));
        //分页
        int page = 0;
        int size = dto.getSize();

        //  int page = (int) dto.getIndex();

        PageRequest request = PageRequest.of(page, size);
        query.with(request);

        //排序分局时间
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);

        List<ApCommentRepay> commentList = mongoTemplate.find(query, ApCommentRepay.class);

        // 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
        ApUser user = AppThreadLocalUtils.getUser();

        if (user != null) {
            ArrayList<ApCommentRepayVO> list = new ArrayList<>();

            for (ApCommentRepay apComment : commentList) {
                ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
                Query query2 = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apComment.getId()));
                ApCommentRepayLike like = mongoTemplate.findOne(query2, ApCommentRepayLike.class);
                if (like != null) {
                    BeanUtils.copyProperties(apComment, apCommentRepayVO);
                    apCommentRepayVO.setOperation((short) 0);
                } else {
                    BeanUtils.copyProperties(apComment, apCommentRepayVO);
                }
                list.add(apCommentRepayVO);
            }
            return ResponseResult.okResult(list);

        }

        return ResponseResult.okResult(commentList);
    }
    /**
     * 保存回复
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {

        if (dto.getCommentId() == null || dto.getContent() == null || "".equals(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "回复需要先登录");
        }
        //校验字符不能大于140个字符
        if (dto.getContent().length() > 140) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论字数不能大于140字");
        }
        //   TODO  阿里云校验评论信息
        try {
            ScanResult scanResult = greenScan.greenTextScan(dto.getContent());
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    // 失败
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章内容中包含违规词汇: " + scanResult.getLabel());
                    //  updateWmNews(WmNews.Status.FAIL.getCode(), "文章内容中包含违规词汇: " + scanResult.getLabel(), wmNews);
                    break;
                case "review":
                    // 人工
                    break;
                case "pass":
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"校验出错");
        }


        //远程查询挡墙登陆用户信息
        ResponseResult<ApUser> user1 = userFeign.findUserById(user.getId());
        ApUser data = user1.getData();

        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"找不到评论的消息");
        }
        //创建评论回复消息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(data.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);


        if (apComment.getReply()==null || apComment.getReply()==0){
            apComment.setReply(1);
        }else {
            apComment.setReply(apComment.getReply()+1);
        }
        //修改评论中回复的数量
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    /**
     * 点赞回复的评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //校验参数
        if (dto.getCommentRepayId() == null || dto.getOperation() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getOperation().intValue() != 0 && dto.getOperation().intValue() != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "点赞方式只能为0或者1");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "点赞需要先登录");
        }

        //校验回复信息是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        //根据回复新消息id查询消息
        ApCommentRepay apComment = mongoTemplate.findOne(query, ApCommentRepay.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "查询不到评论回复信息");
        }
        //查询有没有点赞信息
        Query query2 = Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId").is(user.getId()));
        ApCommentRepayLike commentLike = mongoTemplate.findOne(query2, ApCommentRepayLike.class);
        //如果等于0说明是点赞信息
        if (dto.getOperation().intValue() == 0) {
            if (commentLike != null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
            }
            //创建点赞信息
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentRepayLike);
            if (apComment.getLikes() == null) {
                apComment.setLikes(1);
            } else {
                apComment.setLikes(apComment.getLikes() + 1);
            }
            mongoTemplate.save(apComment);
        }
        //取消点赞
        if (dto.getOperation().intValue() == 1) {
            if (commentLike == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请先点赞");
            }
            mongoTemplate.remove(query2,ApCommentRepayLike.class );
            if (apComment.getLikes() == null || apComment.getLikes() < 1) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "点赞数为0不能再减");
            }
            apComment.setLikes(apComment.getLikes() - 1);
            mongoTemplate.save(apComment);
        }

        HashMap<String, Integer> map = new HashMap<>();
        map.put("likes", apComment.getLikes());
        return ResponseResult.okResult(map);
    }
}
